package com.firesys.httpserver;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;

public class FileUtil {
    private String SDpath;

    public String getSDpath() {
	return SDpath;
    }

    public FileUtil() {
	SDpath = Environment.getExternalStorageDirectory().toString();// 得到外部储存设备目录
    }

    /**
     * 在SD卡上创建文件
     * 
     * @param filename
     *            文件名
     * @return
     * @throws IOException
     */
    public File createSDfile(String filename) throws IOException {
	File file = new File(SDpath + filename);
	file.createNewFile();
	return file;

    }

    /**
     * 在SD卡上创建目录
     * 
     * @param dirname
     *            目录名
     * @return
     */
    public File createSDDir(String dirname) {
	File dir = new File(SDpath + dirname);
	dir.mkdir();
	return dir;

    }

    /**
     * 判断SD卡上的文件夹是否存在
     * 
     * @param filename
     * @return
     */
    public boolean isFileExist(String filename) {

	File file = new File(SDpath + filename);
	return file.exists();

    }

    /**
     * 将inputStream 数据写入到SD卡中
     * 
     * @param path
     * @param filename
     * @param is
     * @return
     */
    public File writeSD(String path, String filename, InputStream is) {
	File file = null;
	OutputStream os = null;

	try {
	    System.out.println(SDpath + path + "/" + filename);
	    file = new File(SDpath + path + "/" + filename);
	    if (file.exists()) {
		file.createNewFile();
	    }

	    os = new FileOutputStream(file);
	    byte[] buffer = new byte[1024];
	    while (is.read(buffer) != -1) {

		os.write(buffer);
	    }
	    os.flush();
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	} finally {
	    try {
		os.close();
	    } catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	}
	return file;

    }
}
